package cn.chenfeifx.checker.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class MD5Checker {

    public static String toHexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static String getFileMD5(String filePath) {
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            byte[] bytes = new byte[1024];
            MessageDigest md = MessageDigest.getInstance("MD5");
            int numBytesRead;
            while ((numBytesRead = is.read(bytes)) != -1) {
                md.update(bytes, 0, numBytesRead);
            }
            byte[] digest = md.digest();
            return toHexString(digest);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) {
        String filePath = "path/to/your/file";
        String md5Value = getFileMD5(filePath);

        // 已知的 MD5 值
        String knownMD5Value = "known_md5_value_here";

        // 判断文件的 MD5 是否重复
        if (md5Value != null && md5Value.equals(knownMD5Value)) {
            System.out.println("文件重复");
        } else {
            System.out.println("文件不重复");
        }
    }
}